package com.bf.zfb_api.util;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.bf.zfb_api.domain.ZfbAlipayConfig;
import com.bf.zfb_api.qrcode.QRCodeUtil;
import com.bf.zfb_api.qrcode.QrCodeResponse;
import com.bf.zfb_api.qrcode.QrResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author：张浩东
 * @Phone：15096207164
 * @QQ：1367048164
 * @E-mail：1367048164@qq.com
 * @date:2021-06-12 18:37
 */
@Slf4j
public class PayUtil {

    /**
     * h5/微信公众号等支付
     * @param model
     * @param zfbAlipayConfig
     * @return
     */
    public static String aliH5Pay(AlipayTradeWapPayModel model, ZfbAlipayConfig zfbAlipayConfig) {
        // 1: 获取阿里请求客户端
        AlipayClient alipayClient = getAlipayClient(zfbAlipayConfig);
        // 2: 获取阿里请求对象
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        // 3：设置请求参数的集合，最大长度不限
        request.setBizModel(model);
        // 设置异步回调地址
        request.setNotifyUrl(zfbAlipayConfig.getNotify_url());
        // 设置同步回调地址
        request.setReturnUrl(zfbAlipayConfig.getReturn_url());
        //3.去支付
        AlipayTradeWapPayResponse alipayResponse = null;
        try {
            return alipayClient.pageExecute(request).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 面对面扫码付款
     * @param alipayTradePrecreateModel
     * @param zfbAlipayConfig
     * @return
     */
    public static byte[] aliTwoDimensionalBarcodePayment(AlipayTradePrecreateModel alipayTradePrecreateModel, ZfbAlipayConfig zfbAlipayConfig) {
        try {
            QrCodeResponse qrCodeResponse = qrcodePay(alipayTradePrecreateModel, zfbAlipayConfig);

            //7 二维码合成
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            String logopath = "";

            //获取二维码
            BufferedImage buffImg = QRCodeUtil.encode(qrCodeResponse.getQr_code(), logopath, false);
            ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
            ImageIO.write(buffImg, "JPEG", imageOut);
            imageOut.close();
            ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
            return FileCopyUtils.copyToByteArray(input);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("PayServiceImpl的aliTwoDimensionalBarcodePayment异常e：" + ex.toString());
            return null;
        }
    }


    /**
     * 退款
     * @param model
     * @param zfbAlipayConfig
     * @return
     */
    public static String aliRefund(AlipayTradeRefundModel model, ZfbAlipayConfig zfbAlipayConfig){
        // 1: 获取阿里请求客户端
        AlipayClient alipayClient = getAlipayClient(zfbAlipayConfig);
        // 2: 获取阿里请求对象
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        // 3：设置请求参数的集合，最大长度不限
        request.setBizModel(model);
        //3.去支付
        AlipayTradeRefundResponse alipayResponse = null;
        try {

            alipayResponse = alipayClient.execute(request);
            if (alipayResponse.isSuccess() && alipayResponse.getFundChange().equalsIgnoreCase("Y")) {
                // 成功
                log.info("退款成功:" + alipayResponse.getBody());
                return alipayResponse.getBody();
            } else {
                // 失败
                log.info("退款失败");
                return "退款失败";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "退款失败";
        }
    }

    /**
     * 订单查询
     * @param model
     * @param zfbAlipayConfig
     * @return
     */
    public static String aliQuery(AlipayTradeQueryModel model, ZfbAlipayConfig zfbAlipayConfig){

        // 1: 获取阿里请求客户端
        AlipayClient alipayClient = getAlipayClient(zfbAlipayConfig);
        // 2: 获取阿里请求对象
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        // 3：设置请求参数的集合，最大长度不限
        request.setBizModel(model);
        //3.去支付
        AlipayTradeQueryResponse alipayResponse = null;
        try {
            alipayResponse =  alipayClient.execute(request);
            if(alipayResponse.isSuccess()){
                System.out.println("调用成功:"+alipayResponse.getBody() );
                return  alipayResponse.getBody();
            } else {
                System.out.println("调用失败");
                return  "调用失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  "调用失败";
    }

    /**
     * 退款查询
     * @param model
     * @param zfbAlipayConfig
     * @return
     */
    public static String aliRefundQuery(AlipayTradeFastpayRefundQueryModel model, ZfbAlipayConfig zfbAlipayConfig){

        // 1: 获取阿里请求客户端
        AlipayClient alipayClient = getAlipayClient(zfbAlipayConfig);
        // 2: 获取阿里请求对象
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        // 3：设置请求参数的集合，最大长度不限
        request.setBizModel(model);
        //3.去支付
        AlipayTradeFastpayRefundQueryResponse alipayResponse = null;
        try {
            alipayResponse =  alipayClient.execute(request);
            if(alipayResponse.isSuccess()){
                System.out.println("调用成功:"+alipayResponse.getBody() );
                return  alipayResponse.getBody();
            } else {
                System.out.println("调用失败");
                return  "调用失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  "调用失败";
    }

    /**
     * 扫码运行代码
     * 验签通过返回QrResponse
     * 失败打印日志信息
     * 参考地址：https://opendocs.alipay.com/apis/api_1/alipay.trade.app.pay
     *
     * @param model
     * @return
     */
    public static QrCodeResponse qrcodePay(AlipayTradePrecreateModel model, ZfbAlipayConfig zfbAlipayConfig) {
        // 1: 获取阿里请求客户端
        AlipayClient alipayClient = getAlipayClient(zfbAlipayConfig);
        // 2: 获取阿里请求对象

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 3：设置请求参数的集合，最大长度不限
        request.setBizModel(model);
        // 设置异步回调地址
        request.setNotifyUrl(zfbAlipayConfig.getNotify_url());
        // 设置同步回调地址
        request.setReturnUrl(zfbAlipayConfig.getReturn_url());
        AlipayTradePrecreateResponse alipayTradePrecreateResponse = null;
        try {
            alipayTradePrecreateResponse = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info(e.toString());
        }
        QrResponse qrResponse = JSON.parseObject(alipayTradePrecreateResponse.getBody(), QrResponse.class);
        return qrResponse.getAlipay_trade_precreate_response();
    }

    /**
     * 获取AlipayClient对象
     *
     * @return
     */
    private static AlipayClient getAlipayClient(ZfbAlipayConfig zfbAlipayConfig) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient =
                new DefaultAlipayClient(zfbAlipayConfig.getGatewayUrl(), zfbAlipayConfig.getApp_id(), zfbAlipayConfig.getMerchant_private_key(),
                        "JSON", zfbAlipayConfig.getCharset(), zfbAlipayConfig.getAlipay_public_key(), zfbAlipayConfig.getSign_type());
        return alipayClient;
    }
}
